'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 走马灯定时发送信息
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var moment = require('moment');
var _ = require('lodash');
var marqueeModel = require('../../models/marqueeModel.js');
var Code = require('../../consts/code.js');
var chatMgr = require('../../mgr/chatMgr.js');
var marqueeService = require('../../services/marqueeService.js');

var run_cnt = 0;

module.exports = function () {
    var marquee_all_list = [];
    if (run_cnt > 0) {
        run_cnt--;
        return;
    }
    async.waterfall(
        [
             function (cb) {
                marqueeModel.removeInvlid(function (err) {
                    cb(err);
                });
             },

            function (cb) {
                marqueeModel.find(function (err, res) {
                    marquee_all_list = res;
                    cb();
                });
            },
            function (cb) {
                run_cnt = 5;
                if (_.size(marquee_all_list) <= 0) {
                    return cb();
                }

                var now_msg_item = marqueeService.getMarqueeMsg(marquee_all_list);
                if (!now_msg_item) {
                    return cb();
                }

                // 推送跑马灯信息
                if (now_msg_item.is_time >= 1 && now_msg_item.times >= 1) {
                    now_msg_item.create_time += now_msg_item.interval_time;
                }
                chatMgr.sendMarquee(now_msg_item, function (err, res) {
                    if (!!err) {
                        console.error(err);
                        cb();
                    } else {
                        now_msg_item.times--;
                        now_msg_item.save(cb);
                    }
                });

            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
            }
            run_cnt = 0;
        }
    );
};

// 数据库中移除信息
var _remove = function (remove_id, cb) {
    marqueeModel.del(remove_id, cb);
};
